<%@ page pageEncoding="UTF-8"%>
<%@ include file="/common/token.jsp"%>
<%@ include file="/common/user.jsp"%>
<%
	Integer uid = token.getUid();
	String date = input.getDesc("date", "");
	String isDone = input.getDesc("is_done", "0");
	List<String> min = QBuilder.db("basedb").select("min(DATE_FORMAT(start,'%Y-%m-%d'))").from("Arrangement").where(new Where("hospital=", hospital).and("status=", STATUS_ENABLE).and("isDone=", isDone).and("partner=", uid)).query().getResultObj();
	if (isEmpty(min)) {
		msg = new Message(30041, "0".equals(isDone) ? "暂无未完成日程" : "暂无已完成日程");
		msg.put("data", new ArrayList());
		Tools.encryptPrint(out, msg);
		return;
	}
	if ("".equals(date)) {
		List<String> max = QBuilder.db("basedb").select("max(DATE_FORMAT(start,'%Y-%m-%d'))").from("Arrangement").where(new Where("hospital=", hospital).and("status=", STATUS_ENABLE).and("isDone=", isDone).and("partner=", uid)).query().getResultObj();
		if (isEmpty(max)) {
			msg = new Message(30041, "0".equals(isDone) ? "暂无未完成日程" : "暂无已完成日程");
			msg.put("data", new ArrayList());
			Tools.encryptPrint(out, msg);
			return;
		}
		date = max.get(0);
	}
	List<Arrangement> list = new ArrayList<Arrangement>();
	int count = 1;
	String endDate = before(date, - (count++) * 10);
	while(isEmpty(list)) {
		list = QBuilder.db("basedb").select().from("Arrangement").where(new Where("hospital=", hospital).and("status=", STATUS_ENABLE).and("isDone=", isDone).and("partner=", uid).and("start <=", date).and("start>", endDate)).order("start", QBuilder.desc).query().getResultObj();
		Date _endDate = DateUtil.parseDate(endDate);
		Date minDate = DateUtil.parseDate(min.get(0));
		if (_endDate.before(minDate) || !isEmpty(list)) {
			break;
		}
		endDate = before(date, - (count++) * 10);
	}
	
	if (isEmpty(list)) {
        msg = new Message(30041, "0".equals(isDone) ? "暂无未完成日程" : "暂无已完成日程");
        msg.put("data", new ArrayList());
        Tools.encryptPrint(out, msg);
        return;
    }
	List<Map> result = new ArrayList<Map>();
    for (int i = 0; i < list.size(); i++) {
        Arrangement ag = list.get(i);
        Map map = Tools.toMap(ag);
        map.put("create", uid.equals(ag.getUid()));
        result.add(map);
    }
    if (isEmpty(result)) {
        msg = new Message(30041, "暂无日程");
    }
	Map map = new HashMap();
	map.put("date", endDate);
	map.put("result", result);
    msg.put("data", map);
    Tools.encryptPrint(out, msg);
%>